package com.example.connecting_dots_android;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;

/**
 * class to control the background image of the application 
 */
public class BackgroundImageListener implements OnClickListener {
	private int mImageId;
	private int mBackgroundImageId = 0;
	private Context mContext;
	private View mLayout;
	
	public BackgroundImageListener(Context context, int imageId, View layout) {
		this.mImageId = imageId;
		this.mContext = context;
		this.mLayout = layout;
	}

	@Override
	public void onClick(View view) {
		view.startAnimation(AnimationUtils.loadAnimation(mContext, R.drawable.image_animation));
		changeBackground(mLayout, mImageId);
	}

	/**
	 * method to change the background image
	 * @param layout
	 * @param imageId
	 */
	private void changeBackground( View layout, int imageId) {
		// set chosen picture
		mBackgroundImageId = getBackgroundImageId(imageId);
		layout.setBackgroundResource(mBackgroundImageId);

		setBakgroundImage(imageId);
	}

	/**
	 * method to set the background for the application
	 * @param imageId
	 */
	private void setBakgroundImage(int imageId) {
		// set chosen picture to shared preferences
		SharedPreferences mySharedPreferences = mContext.getSharedPreferences(
				"background", Activity.MODE_PRIVATE);
		SharedPreferences.Editor editor = mySharedPreferences.edit();
		editor.putInt("myBackgroundImage", imageId);
		editor.commit();
	}
	
	/**
	 * method to get an id for a background image
	 * @param imageId
	 * @return
	 */
		private int getBackgroundImageId(int imageId){
			if(imageId<Constants.backgroundsIds.length)
				return Constants.backgroundsIds[imageId];
			else
				return Constants.backgroundsIds[0];
		}

}
